﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CompileApp.Models;

public static class Constant
{
    private static readonly HashSet<string> Keywords = new HashSet<string>()
    {
        "int", "double", "const", "for", "if", "else", "return", "continue",
        "break", "while", "void", "and", "or"
    };

    private static readonly HashSet<string> Operators = new HashSet<string>()
    {
        "+", "-", "*", "/", "<", "+=", "-=", "*=", "/=", "<=", "=", "%", "%=", "<<", "<<="
    };

    private static readonly HashSet<string> Delimiters = new HashSet<string>()
    {
        "(", ")", "{", "}", ";", ",", "[", "]"
    };

    private static readonly HashSet<char> NormalChars = new HashSet<char>()
    {
        'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A',
        'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    };

    private static readonly HashSet<char> NormalNums = new HashSet<char>()
    {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    };

    private static readonly HashSet<char> NormalNumsExtra = new HashSet<char>()
    {
        'E', '-', '+', 'i', '.'
    };

    public static bool IsValid(string str)
    {
        if (str.Equals("\n") || str.Equals("\t") || String.IsNullOrWhiteSpace(str))
        {
            return false;
        }

        return true;
    }

    public static bool IsId(string str)
    {
        if (str.Length <= 0 || NormalNums.Contains(str[0]))
        {
            return false;
        }

        foreach (var c in str)
        {
            if (!NormalChars.Contains(c))
            {
                return false;
            }
        }

        return true;
    }

    public static bool IsNum(string str)
    {
        if (str.Length == 0)
        {
            return false;
        }

        foreach (var c in str)
        {
            if (!(NormalNums.Contains(c) || NormalNumsExtra.Contains(c)))
            {
                return false;
            }
        }

        if ((str.Contains('+') || str.Contains('-')) && !(str.Contains('i') || str.Contains('E')))
        {
            return false;
        }

        return true;
    }

    public static string FindType(string str)
    {
        string type = "";

        if (Keywords.Contains(str))
        {
            type = "关键字";
        }
        else if (IsId(str))
        {
            type = "标识符";
        }
        else if (Operators.Contains(str))
        {
            type = "操作符";
        }
        else if (!IsValid(str) || Delimiters.Contains(str))
        {
            type = "界符";
        }
        else if (IsNum(str))
        {
            type = "常量";
        }
        else
        {
            type = "错误";
        }

        return type;
    }
}